package com.zqh.lockSupport;

/**
 * @author 曾庆红
 * {@code @date} 2023-10-18 07:40
 */

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * 实现一个容器，提供两个方法 add，size，写两个线程：
 * 线程1，添加10个元素到容器中
 * 线程2，实时监控元素个数，当个数到5个时，线程2给出提示并结束
 */
public class T2 {
    List<Object> list = new ArrayList<>();
    public void add(Object o){
        list.add(o);
    }
    public int size(){
        return list.size();
    }
    public static void main(String[] args) {
        T2 t2 = new T2();
        Thread tt2 = new Thread(()->{
            if(t2.size() != 5){
                LockSupport.park();
            }
            System.out.println("tt2 end");
        },"tt2");
        tt2.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread tt1 = new Thread(()->{
            for(int i = 1; i<=10; i++){

                t2.add(new Object());
                System.out.println("tt1 add "+i);
                if(i == 5){
                    LockSupport.unpark(tt2);
                }

            }
            System.out.println("tt1 end");
        });
        tt1.start();
    }
}
